package com.gitee.dolt.utils;

import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.MultimediaInfo;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.math.BigDecimal;

/**
 * 视频工具类
 */
@Slf4j
public class VideoUtils {

    /**
     * 读取毫秒时长
     *
     * @param videoPath
     * @return
     */
    public static Long getDuration(String videoPath) {
        MultimediaInfo m = getMultimediaInfo(videoPath);
        return m == null ? null : m.getDuration();
    }

    /**
     * 读取秒时长
     *
     * @param videoPath 视频路径
     * @return
     */
    public static Long getSecondDuration(String videoPath) {
        Long duration = getDuration(videoPath);
        return duration == null ? null : duration / 1000;
    }

    /**
     * 读取格式化时长
     *
     * @param videoPath 视频路径
     * @return
     */
    public static String getFormatDuration(String videoPath) {
        Long secondDuration = getSecondDuration(videoPath);
        return secondDuration == null ? null : durationFormatToString(BigDecimal.valueOf(secondDuration));
    }

    /**
     * 获取基本信息
     *
     * @param videoPath 视频路径
     * @return
     */
    public static MultimediaInfo getMultimediaInfo(String videoPath) {
        File file = new File(videoPath);
        Encoder encoder = new Encoder();
        MultimediaInfo m = null;
        try {
            m = encoder.getInfo(file);
        } catch (Exception e) {
            log.warn("获取MultimediaInfo失败,videoPath:{}", videoPath);
        }
        return m;
    }

    /**
     * 将视频时长转换成"00:00:00"的字符串格式
     *
     * @param duration 视频时长（单位：秒）
     * @return
     */
    private static String durationFormatToString(BigDecimal duration) {
        BigDecimal nine = BigDecimal.valueOf(9);
        BigDecimal sixty = BigDecimal.valueOf(60);

        BigDecimal second = duration.divideAndRemainder(sixty)[1];
        BigDecimal minute = duration.subtract(second).divide(sixty).divideAndRemainder(sixty)[1];
        BigDecimal hour = duration.subtract(second).divideToIntegralValue(BigDecimal.valueOf(3600));

        String str = "";
        if (hour.compareTo(nine) > 0) {
            str += hour.intValue() + ":";
        } else {
            str += "0" + hour.intValue() + ":";
        }
        if (minute.compareTo(nine) > 0) {
            str += minute.intValue() + ":";
        } else {
            str += "0" + minute.intValue() + ":";
        }
        if (second.compareTo(nine) > 0) {
            str += second.intValue();
        } else {
            str += "0" + second.intValue();
        }
        return str;
    }
}
